import 'dart:math';

import 'package:flutter/material.dart' hide Page;
import 'package:flutter/cupertino.dart' hide Page;
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kunlun_gas/AppViews/EngineerOrderView/engineer_mater_add_view/page.dart';
import 'package:kunlun_gas/AppViews/FixOrderView/fix_history_view/page.dart';
import 'package:kunlun_gas/AppViews/MainView/order_transfer/fixworker_list_view/page.dart';
import 'package:kunlun_gas/AppViews/OrderView/order_history_view/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/order_result_view/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/patrol_order_list/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/patrol_plan_list/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/reason_view/page.dart';
import 'package:kunlun_gas/AppViews/PatrolOrderView/sign_in_view/page.dart';
import 'package:kunlun_gas/AppViews/UserLogin/staff_login_view/page.dart';
import 'package:kunlun_gas/AppViews/new_version/gas_order/bluetooth_save_page/page.dart';
import 'package:kunlun_gas/AppViews/new_version/gas_order/machine_order/page.dart';
import 'package:kunlun_gas/AppViews/new_version/gas_order/nb_order/page.dart';
import 'package:kunlun_gas/AppViews/new_version/gas_order/xa_ble_save_page/page.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:convert';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

//import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:permission/permission.dart';
import 'dart:io';
import 'package:azlistview/azlistview.dart';

import 'AppViews/EngineerOrderView/engineer_gas_result_view/page.dart';
import 'AppViews/EngineerOrderView/engineer_gas_view/page.dart';
import 'AppViews/EngineerOrderView/engineer_indoor_reason_view/page.dart';
import 'AppViews/EngineerOrderView/engineer_result_page/page.dart';
import 'AppViews/EngineerOrderView/install_type_edit/page.dart';
import 'AppViews/EngineerOrderView/meter_add_view/page.dart';
import 'AppViews/EngineerOrderView/page.dart';
import 'AppViews/MainView/engineer_list_view/page.dart';
import 'AppViews/OrderView/order_history_view/install_history_detail_view/page.dart';

import 'PublicSource/widgets/bottom_select_page/page.dart';

import 'PublicSource/widgets/edit_page/page.dart';

///自定义文件
import 'config/config.dart';
import 'PublicSource/widgets/common_widget.dart';
import 'PublicSource/utils/common_utils.dart';
import 'PublicSource/network/common_network.dart';
import 'PublicSource/UserInfo/user_info_entity.dart';
import 'AppViews/MainView/model/main_view_model.dart';
import 'AppViews/PatrolOrderView/model/patrol_order_model.dart';
//import 'PublicSource/location_manager/location_manager.dart';

///全局store
import 'PublicSource/global_store/state.dart';
import 'PublicSource/global_store/store.dart';
import 'PublicSource/global_store/action.dart';
import 'package:shared_preferences/shared_preferences.dart';

///各个页面
import 'PublicSource/widgets/webview_flutter_page/page.dart';
import 'AppViews/MainView/page.dart';
import 'AppViews/MainView/community_list/page.dart';
import 'AppViews/MainView/check_list/page.dart';
import 'AppViews/MainView/search_view/page.dart';
import 'AppViews/MainView/search_view/search_result/page.dart';
import 'AppViews/UserCenter/page.dart';
import 'AppViews/UserLogin/page.dart';
import 'AppViews/UserCenter/user_account/page.dart';
import 'AppViews/UserCenter/user_info/page.dart';
import 'AppViews/OrderView/page.dart';
import 'AppViews/OrderView/order_result_view/page.dart';
import 'AppViews/OrderView/order_sign_view/page.dart';
import 'AppViews/UserLogin/user_type_view/page.dart';
import 'AppViews/MainView/order_transfer/page.dart';
import 'AppViews/FixOrderView/page.dart';
import 'AppViews/FixOrderView/fix_result_page/page.dart';
import 'AppViews/MainView/install_view/page.dart';
import 'AppViews/MainView/install_view/community_list/page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'PublicSource/common_localiztions_delegate.dart';
import 'AppViews/OrderView/indoor_reason_view/page.dart';
import 'AppViews/OrderView/order_result_edit/page.dart';
import 'AppViews/MainView/plan_list/page.dart';
import 'AppViews/UserCenter/setting/page.dart';

import 'AppViews/new_version/user_register/page.dart';
import 'AppViews/new_version/gasNo_search/page.dart';
import 'AppViews/new_version/gasNo_search/search_result/page.dart';
import 'AppViews/new_version/BindAccountView/page.dart';
import 'AppViews/new_version/BindAccountView/AccountInfoView/page.dart';
import 'AppViews/new_version/gas_insurance/page.dart';
import 'AppViews/new_version/gasNo_manage/page.dart';
import 'AppViews/new_version/safe_order/page.dart';
import 'AppViews/new_version/safe_report/page.dart';
import 'AppViews/new_version/safe_report/send_report_page/page.dart';
import 'AppViews/new_version/gas_order/page.dart';
import 'AppViews/new_version/gas_order/order_detail_page/page.dart';
import 'AppViews/new_version/feedback/page.dart';
import 'AppViews/new_version/consumer_phone/page.dart';
import 'AppViews/new_version/user_info/page.dart';
import 'AppViews/new_version/edit_info/page.dart';
import 'AppViews/new_version/store_detail/page.dart';
import 'AppViews/new_version/gas_order/bind_bluetooth_page/page.dart';
import 'AppViews/new_version/gas_charge/page.dart';
import 'AppViews/new_version/gas_charge/charge_result_view/page.dart';
import 'AppViews/new_version/gas_charge/alipay_view/page.dart';
import 'AppViews/OrderView/user_info_edit/page.dart';
import 'AppViews/OrderView/photo_upload_view/page.dart';

///程序入口
Widget createApp() {
  return MaterialApp(
    title: ThemeConfig.appTitle,
    debugShowCheckedModeBanner: false,
    theme: ThemeData(
      scaffoldBackgroundColor: ThemeConfig.separeColor,
      fontFamily: 'PingFang SC',
      primaryColor: Color(0xFFFE9140),
      appBarTheme: AppBarTheme(
          iconTheme: IconThemeData(color: Colors.white),
          brightness: Brightness.light),
      cupertinoOverrideTheme: CupertinoThemeData(
        barBackgroundColor: ThemeConfig.mainColor,
      ),
      primaryIconTheme: IconThemeData(color: ThemeConfig.mainColor),
      bottomNavigationBarTheme: BottomNavigationBarThemeData(
        selectedItemColor: ThemeConfig.mainColor,
      ),
    ),
    locale: Locale('zh', 'CN'),
    localizationsDelegates: [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      CommonLocalizationsDelegate(),
    ],
    supportedLocales: [
      Locale('zh', 'CN'),
    ],
    routes: {
      '/': (context) {
        return AppScaffold();
      },
    },
  );
}

class RoutePath {
  static const String mainView = 'MainView';
  static const String webView_FlutterView = 'webView_FlutterView';
  static const String userCenterView = 'userCenterView';
  static const String userLoginView = 'userLoginView';
  static const String userAccountView = 'userAccountView';
  static const String userInfoView = 'userInfoView';
  static const String communityListView = 'communityListView';
  static const String checkListView = 'checkListView';
  static const String searchView = 'searchView';
  static const String searchResultView = 'searchResultView';
  static const String orderView = 'orderView';
  static const String orderResultView = 'orderResultView';
  static const String orderSignView = 'orderSignView';
  static const String userTypeView = 'userTypeView';
  static const String orderTransferView = 'orderTransferView';
  static const String fixOrderView = 'fixOrderView';
  static const String fixResultView = 'fixResultView';
  static const String installView = 'installView';
  static const String selectCommunityView = 'selectCommunityView';
  static const String refuseIndoorView = 'refuseIndoorView';
  static const String orderResultEditView = 'orderResultEditView';
  static const String planListView = 'planListView';
  static const String settingView = 'settingView';
  static const String userRegisterView = 'userRegisterView';
  static const String gasNoSearchResultView = 'gasNoSearchResultView';
  static const String searchAccountView = 'searchAccountView';
  static const String bindAccountView = 'bindAccountView';
  static const String accountInfoView = 'accountInfoView';
  static const String gasInsuranceView = 'gasInsuranceView';
  static const String gasUserAccountView = 'gasUserAccountView';
  static const String safeOrderView = 'safeOrderView';
  static const String sendReportView = 'sendReportView';
  static const String reportProblemView = 'reportProblemView';
  static const String orderListView = 'orderListView';
  static const String orderDetailView = 'orderDetailView';
  static const String userEditInfoView = 'userEditInfoView';
  static const String feedbackView = 'feedbackView';
  static const String hotlineView = 'hotlineView';
  static const String userInfoAccountView = 'userInfoAccountView';
  static const String editInfoView = 'editInfoView';
  static const String storeDetailView = 'storeDetailView';
  static const String bindBlueToothView = 'bindBlueToothView';
  static const String bluetoothSaveView = 'bluetoothSaveView';
  static const String gasChargeView = 'gasChargeView';
  static const String chargeResultView = 'chargeResultView';
  static const String aliPayView = 'aliPayView';
  static const String userInfoEditView = 'userInfoEditView';
  static const String nbOrderView = 'nbOrderView';
  static const String machineOrderView = 'machineOrderView';
  static const String staffLoginView = 'staffLoginView';
  static const String patrolPlanListView = 'patrolPlanListView';
  static const String patrolOrderListView = 'patrolOrderListView';
  static const String patrolSignInView = 'patrolSignInView';
  static const String patrolReasonView = 'patrolReasonView';
  static const String patrolOrderView = 'patrolOrderView';
  static const String patrolOrderResultView = 'patrolOrderResultView';
  static const String fixWorkerListView = 'fixWorkerListView';
  static const String photoUploadView = 'photoUploadView';
  static const String orderHistoryView = 'orderHistoryView';
  static const String installHistoryDetailView = 'installHistoryDetailView';
  static const String fixHistoryView = 'fixHistoryView';
  static const String xaBleSaveView = 'xaBleSaveView';
  static const String engineerGasOpenView = 'engineerGasOpenView';
  static const String engineerIndoorReasonView = 'engineerIndoorReasonView';
  static const String engineerResultView = 'engineerResultView';
  static const String bottomSelectView = 'bottomSelectView';
  static const String engineerOrderView = 'engineerOrderView';
  static const String engineerGasResultView = 'engineerGasResultView';
  static const String installTypeEditView = 'installTypeEditView';
  static const String meterAddView = 'meterAddView';
  static const String engineerMaterAddView = 'engineerMaterAddView';
  static const String editPageView = 'editPageView';
  static const String engineerListView = 'engineerListView';

  ///底部导航栏背景色
  static const Color tableBarBackColor = Color.fromRGBO(255, 255, 255, 1.0);
}

class AppMainRoutes {
  static final AbstractRoutes routes = PageRoutes(
    pages: <String, Page<Object, dynamic>>{
      RoutePath.mainView: MainViewPage(),
      RoutePath.userCenterView: UserCenterPage(),
      RoutePath.userLoginView: UserLoginPage(),
      RoutePath.webView_FlutterView: WebViewPage(),
      RoutePath.userAccountView: UserAccountPage(),
      RoutePath.userInfoView: UserInfoPage(),
      RoutePath.communityListView: CommunityListViewPage(),
      RoutePath.checkListView: CheckListViewPage(),
      RoutePath.searchView: SearchViewPage(),
      RoutePath.searchResultView: SearchResultViewPage(),
      RoutePath.orderView: OrderViewPage(),
      RoutePath.orderResultView: OrderResultViewPage(),
      RoutePath.orderSignView: OrderSignViewPage(),
      RoutePath.userTypeView: UserTypeViewPage(),
      RoutePath.orderTransferView: OrderTransferViewPage(),
      RoutePath.fixOrderView: FixOrderViewPage(),
      RoutePath.fixResultView: FixResultViewPage(),
      RoutePath.installView: InstallViewPage(),
      RoutePath.selectCommunityView: SelectCommunityViewPage(),
      RoutePath.refuseIndoorView: RefuseIndoorPage(),
      RoutePath.orderResultEditView: OrderResultEditPage(),
      RoutePath.planListView: PlanListViewPage(),
      RoutePath.settingView: SettingViewPage(),
      RoutePath.userRegisterView: UserRegisterViewPage(),
      RoutePath.gasNoSearchResultView: GasNoSearchResultViewPage(),
      RoutePath.searchAccountView: SearchAccountViewPage(),
      RoutePath.bindAccountView: BindAccountViewPage(),
      RoutePath.accountInfoView: AccountInfoViewPage(),
      RoutePath.gasInsuranceView: GasInsuranceViewPage(),
      RoutePath.gasUserAccountView: UserAccountViewPage(),
      RoutePath.safeOrderView: SafeOrderViewPage(),
      RoutePath.sendReportView: SendProblemViewPage(),
      RoutePath.reportProblemView: ReportProblemViewPage(),
      RoutePath.orderListView: OrderListViewPage(),
      RoutePath.orderDetailView: OrderDetailListViewPage(),
      RoutePath.userEditInfoView: UserEditInfoViewPage(),
      RoutePath.editInfoView: EditInfoViewPage(),
      RoutePath.feedbackView: FeedbackViewPage(),
      RoutePath.hotlineView: HotLineViewPage(),
      RoutePath.userInfoAccountView: UserAccountPage(),
      RoutePath.storeDetailView: StoreDetailViewPage(),
      RoutePath.bindBlueToothView: BindBlueToothViewPage(),
      RoutePath.bluetoothSaveView: BlueToothSaveViewPage(),
      RoutePath.gasChargeView: GasChargeViewPage(),
      RoutePath.aliPayView: AlipayViewPage(),
      RoutePath.chargeResultView: ChargeReusltViewPage(),
      RoutePath.nbOrderView: NbOrderViewPage(),
      RoutePath.userInfoEditView: UserInfoEditViewPage(),
      RoutePath.machineOrderView: MachineOrderViewPage(),
      RoutePath.staffLoginView: StaffLoginViewPage(),
      RoutePath.patrolPlanListView: PatrolPlanListViewPage(),
      RoutePath.patrolOrderListView: PatrolOrderListViewPage(),
      RoutePath.patrolReasonView: PatrolReasonViewPage(),
      RoutePath.patrolSignInView: PatrolSignInViewPage(),
      RoutePath.patrolOrderView: PatrolOrderViewPage(),
      RoutePath.patrolOrderResultView: PatrolOrderResultViewPage(),
      RoutePath.fixWorkerListView: FixWorkerListViewPage(),
      RoutePath.photoUploadView: PhotoUploadViewPage(),
      RoutePath.orderHistoryView: OrderHistoryViewPage(),
      RoutePath.installHistoryDetailView: InstallHistoryDetailViewPage(),
      RoutePath.fixHistoryView: FixHistoryViewPage(),
      RoutePath.xaBleSaveView: XABleSaveViewPage(),
      RoutePath.engineerGasOpenView: EngineerGasOpenViewPage(),
      RoutePath.engineerIndoorReasonView: EngineerIndoorReasonViewPage(),
      RoutePath.engineerResultView: EngineerResultViewPage(),
      RoutePath.bottomSelectView: BottomSelectViewPage(),
      RoutePath.engineerOrderView: EngineerOrderViewPage(),
      RoutePath.engineerGasResultView: EngineerGasResultViewPage(),
      RoutePath.installTypeEditView: InstallTypeEditViewPage(),
      RoutePath.meterAddView: MeterAddViewPage(),
      RoutePath.engineerMaterAddView: EngineerMaterAddViewPage(),
      RoutePath.editPageView: EditViewPage(),
      RoutePath.engineerListView: EngineerListViewPage(),
    },
    visitor: (String path, Page<Object, dynamic> page) {
      /// XXX
      if (page.isTypeof<GlobalBaseState>()) {
        page.connectExtraStore<GlobalState>(GlobalStore.store,
            (Object pagestate, GlobalState appState) {
          if (pagestate is Cloneable) {
            final Object copy = pagestate.clone();
            final GlobalBaseState newState = copy;
            newState.userInfo = appState.userInfo;
            return newState;
          }
          return pagestate;
        });
      }

      page.enhancer.append(
        viewMiddleware: <ViewMiddleware<dynamic>>[safetyView<dynamic>()],
        adapterMiddleware: <AdapterMiddleware<dynamic>>[
          safetyAdapter<dynamic>()
        ],
        effectMiddleware: [],
        middleware: <Middleware<dynamic>>[logMiddleware<dynamic>()],
      );
    },
  );
}

///
/// 程序主框架
/// _bottomTabs 设置底部导航按钮
/// _pages 设置主页面
/// initState()函数中对应用进行初始化
///

class AppScaffold extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _AppScaffold createState() => _AppScaffold();
}

class _AppScaffold extends State<AppScaffold> {
  int _currentIndex = 0;
  bool _isHandleLogin = false;

  final pageController = PageController();

  ///设置导航栏按钮
  List<BottomNavigationBarItem> _bottomTabs() {
    UserInfoEntity info = GlobalStore.store.getState().userInfo;
    Image.asset('images/login_logo.png');
    Image.asset('images/login_bg.jpg');
    Image.asset('images/center_bg.png');
    return [
      BottomNavigationBarItem(
        icon: IconWithBadge('images/tab_normal_1.png'),
        activeIcon: IconWithBadge('images/tab_press_1.png'),
        title: Text(
          info.isGsUser
              ? '首页'
              : (info.isFixWorker || info.isCheckWorker)
                  ? '任务'
                  : '统计',
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontFamily: 'PingFang SC',
            fontSize: 12,
          ),
        ),
      ),
      BottomNavigationBarItem(
        icon: IconWithBadge('images/tab_normal_2.png'),
        activeIcon: IconWithBadge('images/tab_press_2.png'),
        title: Text(
          '我的',
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontFamily: 'PingFang SC',
            fontSize: 12,
          ),
        ),
      ),
    ];
  }

  ///设置页面
  final List<Widget> _pages = [
    AppMainRoutes.routes.buildPage(RoutePath.mainView, null),
    AppMainRoutes.routes.buildPage(RoutePath.userCenterView, {'isUser': true}),
  ];

  ///初始化用户信息
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  Future<void> autoLogin() async {
    final SharedPreferences prefs = await _prefs;
    String phone = prefs.getString(UserInfoConst.phone) ?? '';
    String password = prefs.getString(UserInfoConst.password) ?? '';
    var number = double.tryParse(phone);

    ///展示用户界面
    if (phone.length == 11 && number != null && phone.startsWith('1')) {
      ResultData res = await CommonNetWork.gasUserLogin(
        phone,
        password,
      );
      if (res.success) {
        UserInfoEntity info = UserInfoEntity.fromGasJson(res.data);
        await CommonUtils.initImageConfig(token: info.token, isGasUser: true);
        ResultData infoRes = await CommonNetWork.gasUserCenterInfo(
            token: info.token, memberID: info.userid);
        if (infoRes.success) {
          info.setGasInfoFromJson(infoRes.data);
          info.password = password;
          info.mobile = phone;
          info.phone = phone;
          info.isGsUser = true;
          GlobalStore.store.dispatch(GlobalActionCreator.onUserLogin(info));
          bus.emit('setGasUser');
          return;
        }
      }
    }

    if (password.length != 0 && phone.length != 0) {
      String userID = prefs.getString(UserInfoConst.userid) ?? '';
      String roleName = prefs.getString(UserInfoConst.position + userID) ?? '';
      if (roleName.isNotEmpty) {
        ResultData res = await CommonNetWork.staffUserLogin(
          phone,
          password,
          roleName,
        );
        if (res.success) {
          UserInfoEntity info = UserInfoEntity.fromStaffJson(res.data);
          await CommonUtils.initImageConfig(
              token: info.token, isGasUser: false);
          info.currentRoleName = roleName;
          info.password = password;
          info.mobile = phone;
          info.isGsUser = false;
          if (info.isCheckWorker) {
            SharedPreferences preferences =
                await SharedPreferences.getInstance();
            int currentPlan =
                preferences.getInt(UserInfoConst.currentPlan + info.userid) ??
                    0;
            info.currentPlan = currentPlan;
            ResultData plans =
                await CommonNetWork.staffCheckPlans(token: info.token);
            if (plans.success) {
              List list = plans.data['data'];
              info.plans = list
                  .map<PlanItemModel>((e) => PlanItemModel.fromJson(e))
                  .toList();
              SuspensionUtil.sortListBySuspensionTag(info.plans);
            }
          }

          if (info.isPatrolWorker) {
            SharedPreferences preferences =
                await SharedPreferences.getInstance();
            int currentPlan = preferences
                    .getInt(UserInfoConst.currentPatrolPlan + info.userid) ??
                0;
            info.currentPatrolPlan = currentPlan;
            ResultData plans =
                await CommonNetWork.staffPatrolPlans(token: info.token);
            if (plans.success) {
              List list = plans.data['data'];
              List<PatrolPlanModel> patrolPlans = list
                  .map<PatrolPlanModel>((e) => PatrolPlanModel.fromJson(e))
                  .toList();
              SuspensionUtil.sortListBySuspensionTag(patrolPlans);
              info.patrolPlans = patrolPlans;
            }
          }

          GlobalStore.store.dispatch(GlobalActionCreator.onUserLogin(info));
          bus.emit('refreshMain');
          return;
        }
      }
    }
    CommonUtils.gotoLoginView(context);
  }

  ///微信初始化
  _initFluwx() async {
    await AmapService.init(
      iosKey: 'f0ae6a2f8ca17227bef57f6124295327',
      androidKey: '68532ce41373d3f5d5d8c5a875eb56b6',
    );
//    await fluwx.registerWxApi(
//        appId: ShareConfig.weChatAppID,
//        doOnAndroid: true,
//        doOnIOS: true,
//        universalLink: 'https://australiaMc/');
//    var result = await fluwx.isWeChatInstalled();
//    print("is installed $result");
  }

  ///检测更新
  _checkVersion() async {
    bus.on('forceUpdate', (arg) {
      launch(arg);
    });
    if (Platform.isAndroid) {
      List<PermissionName> permissionNames = [];
      permissionNames.add(PermissionName.Storage);
      permissionNames.add(PermissionName.Location);
      permissionNames.add(PermissionName.BLE_SCAN);
      var permissions = await Permission.requestPermissions(permissionNames);
    }

    ResultData res = await CommonNetWork.versionCheck();
    if (res.success) {
      List list = res.data;
      if (list.isNotEmpty) {
        var item = list.last;
        String version = CommonUtils.checkNullToString(item['VerVersion']);
        if (version.compareTo(ThemeConfig.version) > 0) {
          int res = await CommonUtils.showVersionDialog(
            context,
            isForce: item['VerIsForce'],
            message: item['VerUpdateNote'],
            url: item['VerDownloadLink'],
          );
          if (res == 1) {
            launch(CommonUtils.checkNullToString(item['VerDownloadLink']));
          }
          return;
        }
      }
    }
  }

  ///更新启动页信息
  _initSplash() async {
//    final SharedPreferences prefs = await _prefs;
//    ResultData res = await CommonNetWork.getSplashModel();
//    if (res.success) {
//      List data = res.data['data'];
//      if (data.length > 0) {
//        Map info = data.last;
//        prefs.setString('splash_model', json.encode(info));
//        DefaultCacheManager manager = DefaultCacheManager();
//        manager.downloadFile(CommonUtils.checkNullToString(info['picname']));
//      } else {
//        prefs.setString('splash_model', null);
//      }
//    }
  }

//Stack（层叠布局）+Offstage组合,解决状态被重置的问题
  Widget _getPagesWidget(int index) {
    return Offstage(
      offstage: _currentIndex != index,
      child: TickerMode(
        enabled: _currentIndex == index,
        child: _pages[index],
      ),
    );
  }

  /// 退出弹框
  Future<bool> _onWillPop() {
    return showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('提示?'),
            content: new Text('确定退出应用程序'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: new Text('否'),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('是'),
              ),
            ],
          ),
        ) ??
        false;
  }

  /// -----------主程序入口-----------   ///
  @override
  void initState() {
    super.initState();
    _checkVersion();
    _initFluwx();
    _initSplash();
    bus.on('gomain', (arg) {
      pageController.jumpToPage(0);
    });

    bus.on('errlogin', (arg) {
      if (!_isHandleLogin) {
        _isHandleLogin = true;
        GlobalStore.store.dispatch(GlobalActionCreator.onUserLogout());
        CommonUtils.showAlertView(context, "登录超时！请重新登录").then((r) {
          Navigator.popUntil(context, ModalRoute.withName('/'));
          pageController.jumpToPage(0);
          CommonUtils.gotoLoginView(context)
              .then((value) => _isHandleLogin = false);
        });
      }
    });

    bus.on('refreshMain', (arg) {
      setState(() {});
    });
    autoLogin();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil()..init(context);
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: RoutePath.tableBarBackColor,
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: _currentIndex,
          items: _bottomTabs(),
          onTap: (index) {
            if (index == 1) {
              GlobalState state = GlobalStore.store.getState();
              if (state.userInfo.userid.length == 0) {
                CommonUtils.gotoLoginView(context);
                return;
              }
            }
            pageController.jumpToPage(index);
            // setState(() {
            //   if (index == 1) {
            //     CommonUtils.checkUserLogin(context, () {
            //       _currentIndex = index;
            //     });
            //   } else
            //     _currentIndex = index;
            // });
          },
        ),
        body: PageView(
          controller: pageController,
          onPageChanged: onPageChanged,
          children: _pages,
          physics: NeverScrollableScrollPhysics(), // 禁止滑动
        ),
        // body: Stack(
        //   children: [
        //     _getPagesWidget(0),
        //     _getPagesWidget(1),
        //   ],
        // ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  void onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}
